package com.ccit.springbootlaw.mapper;

import com.ccit.springbootlaw.pojo.Comment;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.sql.Timestamp;
import java.util.List;

@Mapper
@Repository
public interface CommentMapper {
    // 根据ID查询评论
    @Select("SELECT * FROM comments WHERE id = #{id}")
    Comment findById(int id);

    // 根据用户ID查询评论
    @Select("SELECT * FROM comments WHERE user_id = #{userId}")
    List<Comment> findByUserId(int userId);

    // 根据文章ID查询评论
    @Select("SELECT * FROM comments WHERE article_id = #{articleId}")
    List<Comment> findByArticleId(int articleId);

    // 根据父评论ID查询评论
    @Select("SELECT * FROM comments WHERE parent_id = #{parentId}")
    List<Comment> findByParentId(Integer parentId);

    // 根据创建时间范围查询评论
    @Select("SELECT * FROM comments WHERE created_at BETWEEN #{startTime} AND #{endTime}")
    List<Comment> findByCreatedAtRange(Timestamp startTime, Timestamp endTime);

    // 根据传入的 Comment 实体类内容进行多条件查找
    @Select("<script>" +
            "SELECT * FROM comments " +
            "<where>" +
            "<if test='content != null and content != \"\"'>AND content LIKE CONCAT('%', #{content}, '%')</if>" +
            "<if test='userId != null and userId != 0'>AND user_id = #{userId}</if>" +
            "<if test='articleId != null and articleId != 0'>AND article_id = #{articleId}</if>" +
            "<if test='parentId != null and parentId != 0'>AND parent_id = #{parentId}</if>" +
            "</where>" +
            "</script>")
    List<Comment> findByConditions(Comment conditions);

    // 根据文章 ID 查找父评论为空的评论
    @Select("SELECT * FROM comments WHERE article_id = #{articleId} AND parent_id IS NULL")
    List<Comment> findRootCommentsByArticleId(int articleId);

    // 查询所有评论
    @Select("SELECT * FROM comments")
    List<Comment> findAll();

    // 插入新的评论
    @Insert("INSERT INTO comments (content, user_id, article_id, parent_id, created_at) " +
            "VALUES (#{content}, #{userId}, #{articleId}, #{parentId}, NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertComment(Comment comment);

    // 更新评论
    @Update("<script>" +
            "UPDATE comments " +
            "<set>" +
            "<if test='content != null'>content = #{content},</if>" +
            "<if test='userId != null'>user_id = #{userId},</if>" +
            "<if test='articleId != null'>article_id = #{articleId},</if>" +
            "<if test='parentId != null'>parent_id = #{parentId},</if>" +
            "created_at = NOW()" +
            "</set>" +
            "WHERE id = #{id}" +
            "</script>")
    int updateComment(Comment comment);

    // 删除评论
    @Delete("DELETE FROM comments WHERE id = #{id}")
    int deleteCommentById(int id);
}